import axios from 'axios'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { useUserStore } from '@/store/index.ts'
import { Message } from '@arco-design/web-vue'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

const request = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: import.meta.env.VITE_APP_TIMEOUT || 20000,
  withCredentials: true
})
NProgress.configure({ showSpinner: false })

request.interceptors.request.use(
  async (config) => {
    NProgress.start()
    const userStore = useUserStore()
    if (await userStore.getToken()) {
      config.headers['authorization'] ="Bearer "+ await userStore.getToken()
    }
    //自行实现发送请求前操作
    return config
  },
  (error) => {
    console.error(error)
    Promise.reject(error)
  }
)

request.interceptors.response.use(
  async (res) => {
    //自行实现响应后操作
    const userStore = useUserStore()
    if (res.headers['authorization']) {
      userStore.setToken(res.headers['authorization'])
    }
    const status = res.status
    const result = res.data
    if (status == 200) {
    }
    if (status == 401) {
      Message.error(result?.message || '未登录')
    }
    if (status == 403) {
      Message.error(result?.message || '无权限')
    }
    if (status == 500) {
      Message.error(result?.message || '服务器错误')
    }
    NProgress.done()
    return Promise.resolve(result)
  },
  (error) => {
    return Promise.reject(error)
  }
)
export default request
